//
//  AppDelegate.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/22.
//

import UIKit
import AppTrackingTransparency
import AdSupport
import SwiftyStoreKit
import KeychainAccess
import Bugly
import SwiftUI
import FBSDKCoreKit

let appDelegate = UIApplication.shared.delegate as! AppDelegate

//@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var wn_window: UIWindow?
              
    var wn_application: UIApplication?
    
    var wn_launchOptions: [UIApplication.LaunchOptionsKey: Any]?

    var resignActive = false
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        WNThread.wn_runInMainThread {
            WNBuriedManager.shared.startEvents("open", (CFAbsoluteTimeGetCurrent() - appStartLaunchTime))
        }
//        let center = UNUserNotificationCenter.current()
//        center.delegate = self
//        center.requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in
//            guard granted else { return saveEnableNot(false) }
//            center.getNotificationSettings { settings in
//                guard settings.authorizationStatus == .authorized else { return saveEnableNot(false) }
//                WNThread.wn_runInMainThread {
//                    saveEnableNot(true)
//                    application.registerForRemoteNotifications()
//                }
//            }
//        }
        wn_application = application
        wn_launchOptions = launchOptions
        rootConfig()
        return true
    }
}

//MARK: - 配置项
extension AppDelegate {
    
    func settingAndSDKConfig() {
        /// IQ键盘预览关闭
        IQKeyboardManager.shared().isEnableAutoToolbar = false
        IQKeyboardManager.shared().shouldResignOnTouchOutside = true
        /// 防止按钮连续点击
        UIView.appearance().isExclusiveTouch = true
        UIScrollView.appearance().automaticallyAdjustsScrollIndicatorInsets = false
        UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        // Bugly
        let config = BuglyConfig()
        config.unexpectedTerminatingDetectionEnable = true
        config.reportLogLevel = .error
        config.blockMonitorEnable = true
        config.blockMonitorTimeout = 1.5
        config.version = getAPPVersion()
        config.channel = "ios"
        config.debugMode = true
        config.deviceIdentifier = getUUID()
        Bugly.start(withAppId: WNConfigure.Bugly.appId, developmentDevice: !server.isProduct, config: config)
        Bugly.setUserIdentifier(getUUID())
        /// Realm
        WNRealmManager.shared.configRealm()
        /// SwiftyStoreKit
        storeKitConfig()
        if Date().timeDate > getUpgradeDate()+3*24*60*60 {
            saveUpgradeClose(false)
        }
        _ = Keychain(service: WNConfigure.Keychain.serviceName)
    }
    
    func storeKitConfig() {
        /// 内购未处理的支付事件
        SwiftyStoreKit.completeTransactions(atomically: true) { (purchases) in
            var dic = [String: Any]()
            for purchase in purchases {
                if purchase.productId.hasPrefix("com.dream.novle") {
                    dic["complete"] = 1
                    dic["orderId"] = isAppleLogin() ? getUserIdSubOrderId() : getUuidSubOrderId()
                    switch purchase.transaction.transactionState {
                    case .purchased:
                        if purchase.originalTransaction != nil {
                            dic["otid"] = purchase.originalTransaction?.transactionIdentifier ?? ""
                            dic["otdate"] = purchase.originalTransaction?.transactionDate
                        }
                        let downloads = purchase.transaction.downloads
                        if !downloads.isEmpty {
                            SwiftyStoreKit.start(downloads)
                        }else {
                            dic["code"] = 0
                            dic["msg"] = ""
                            dic["tid"] = purchase.transaction.transactionIdentifier ?? ""
                            dic["tdate"] = purchase.transaction.transactionDate
                            dic["receipt"] = SwiftyStoreKit.localReceiptData?.base64EncodedString()
                            WNSubManager.shared.verifySubscribe(dic)
                        }
                    case .failed:
                        dic["code"] = 2
                        dic["msg"] = "No resotrable purchases"
                        WNSubManager.shared.verifySubscribe(dic)
                    case .restored:
                        WNSubManager.shared.restoreSubscribe(purchase.productId, "6e220e39ae5042fbaf21cb574a78c09c")
                    default: break
                    }
                }else {
                    dic["complete"] = 1
                    dic["orderId"] = isAppleLogin() ? getUserIdOrderId() : getUuidOrderId()
                    switch purchase.transaction.transactionState {
                    case .purchased:
                        let downloads = purchase.transaction.downloads
                        if !downloads.isEmpty {
                            SwiftyStoreKit.start(downloads)
                        }else {
                            dic["code"] = 0
                            dic["msg"] = ""
                            dic["tid"] = purchase.transaction.transactionIdentifier ?? ""
                            dic["receipt"] = SwiftyStoreKit.localReceiptData?.base64EncodedString()
                            if (dic["orderId"] as! String).hasPrefix("limited_") {
                                WNLimitedPayManager.shared.verifyLimitedRecharge(dic)
                            }else if (dic["orderId"] as! String).hasPrefix("chapter_") {
                                WNReadPayManager.shared.verifyReadRecharge(dic)
                            }else {
                                WNPayManager.shared.verifyRecharge(dic)
                            }
                        }
                    case .failed:
                        dic["code"] = 2
                        dic["msg"] = "No resotrable purchases"
                        if (dic["orderId"] as! String).hasPrefix("limited_") {
                            WNLimitedPayManager.shared.verifyLimitedRecharge(dic)
                        }else if (dic["orderId"] as! String).hasPrefix("chapter_") {
                            WNReadPayManager.shared.verifyReadRecharge(dic)
                        }else {
                            WNPayManager.shared.verifyRecharge(dic)
                        }
                    case .restored:
                        WNPayManager.shared.restorePurchase()
                    default: break
                    }
                }
            }
        }

        SwiftyStoreKit.updatedDownloadsHandler = { downloads in
            let contentURLs = downloads.compactMap { $0.contentURL }
            if contentURLs.count == downloads.count {
                SwiftyStoreKit.finishTransaction(downloads[0].transaction)
            }
        }
    }
    
    /// IDFA的请求
    func requestIDFA() -> String {
        var idfa = ""
        let manager = ASIdentifierManager.shared()
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                if status == .authorized {
                    idfa = manager.advertisingIdentifier.uuidString
                    Settings.shared.isAdvertiserTrackingEnabled = true
                }
            })
        }else {
            if manager.isAdvertisingTrackingEnabled {
                idfa = manager.advertisingIdentifier.uuidString
                Settings.shared.isAdvertiserTrackingEnabled = true
            }
        }
        return idfa
    }

    /// 三方初始化 fb初始化
    func threeConfig(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        ApplicationDelegate.shared.initializeSDK()
        AppLinkUtility.fetchDeferredAppLink { (url, error) in
            if let error = error {
                print("Received error while fetching deferred app link %@", error)
            }
            if let url = url {
                WNThread.wn_delay(0) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
        }
        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        Settings.shared.isAdvertiserTrackingEnabled = true
        Settings.shared.isAdvertiserIDCollectionEnabled = true
        Settings.shared.isAutoLogAppEventsEnabled = true
    }

    func rootConfig() {
        wn_window = UIWindow(frame: Screen.bounds)
        if ADModel.deserialize(from: getAdJson())?.bookId == nil {
            let vc = WNTabBarVC()
            UIView.transition(with: wn_window!, duration: 0, options: .transitionCrossDissolve, animations: {
                self.wn_window?.rootViewController = WNBaseNaviVC(rootViewController: vc)
                self.wn_window?.makeKeyAndVisible()
            }) { finish in
                if finish {
                    vc.handleConfig()
                }
            }
        }else {
            wn_window?.rootViewController = WNBaseNaviVC(rootViewController: WNAdvertVC())
            wn_window?.makeKeyAndVisible()
        }
    }
}
